<template>
  <div class="bigbox">
    <div>
      <table>
        <thead>
          <tr>
            <th>序号</th>
            <th>图书名称</th>
            <th>出版日期</th>
            <th>价格</th>
            <th>购买数量</th>
            <th>操作</th>
          </tr>
        </thead>
        <h2 style="text-align: center" v-if="ish2">购物车为空</h2>
        <tbody v-if="istable">
          <tr v-for="(item, index) in books" :key="item.id">
            <td>{{ item.id }}</td>
            <td>{{ item.bookName }}</td>
            <td>{{ item.publishedTime }}</td>
            <td>{{ item.price }}</td>
            <td class="bqb">
              <input
                type="button"
                value="-"
                :disabled="item.quantity === 1"
                @click="item.quantity--"
              />
              <input class="quantity" type="text" v-model="item.quantity" />
              <input type="button" value="+" @click="item.quantity++" />
            </td>
            <td><input type="button" value="移除" @click="spliceBook(index)" /></td>
          </tr>
        </tbody>
      </table>
      总价: <span class="total">{{ total }}</span> ￥
    </div>
  </div>
</template>

<script setup>
import { computed, reactive, ref } from 'vue'

let initBooks = [
  { id: 1, bookName: '《JavaScript高级编程》', publishedTime: '2006-9', price: 85.0, quantity: 1 },
  { id: 2, bookName: '《C语言基础》', publishedTime: '2006-2', price: 59.0, quantity: 1 },
  { id: 3, bookName: '《Java高级语言》', publishedTime: '2008-10', price: 39.0, quantity: 1 },
  { id: 4, bookName: '《代码大全》', publishedTime: '2006-3', price: 128.0, quantity: 1 },
  {
    id: 5,
    bookName: '《你不知道的JavaScript》',
    publishedTime: '2014-8',
    price: 88.0,
    quantity: 1,
  },
]
let books = reactive(initBooks)
let istable = ref(true)
let ish2 = ref(false)
function spliceBook(id) {
  books.splice(id, 1)
  if (books.length === 0) {
    ish2.value = true
    istable.value = false
  } else {
    istable.value = true
    ish2.value = false
  }
}
const total = computed(() => {
  let sum = ref(0)
  books.forEach((item) => {
    sum.value += item.price * item.quantity
  })
  return sum
})
</script>

<style scoped>
* {
  margin: 0px;
  padding: 0px;
}
.bigbox {
  display: flex;
  justify-content: center;
  align-items: center;
  min-width: calc(100vw - 200px);
  min-height: calc(100vh - 160px);
}
tbody {
  text-align: center;
}
table,
tr,
th,
td {
  border: 1px solid;
  border-collapse: collapse;
}
.quantity {
  width: 20px;
  text-align: center;
}
.bqb {
  display: flex;
  align-items: center;
  justify-content: center;
}
.total {
  font-size: 20px;
  font-weight: 900;
}
</style>
